//
//  SEGMonthCardPayViewController.m
//  ExcellentHome
//
//  Created by liangxinqiang on 16/1/7.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "SEGPayToolView.h"
#import "SEGMonthCardPayViewController.h"
#import "SEGMonthCardRecordViewController.h"
#import "MonthCardRequestModel.h"
#import "SEGBillDeatilDisFeeView.h"

@interface SEGMonthCardPayViewController ()
@property (nonatomic, strong) SEGPayToolView* payToolView;
@property (nonatomic, assign) CGFloat totalPrice;
@property (nonatomic, strong) SEGBillDeatilDisFeeView* disFeeView;
@end

@implementation SEGMonthCardPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"月卡缴费";
    [self setupUI];
    [self showCustomNavigationBackButton];
    
    _fieldArr = [[NSArray alloc] init];
    _fieldArr = [self.dataDic objectForKey:@"parkingPlaceList"];
}

- (void)setupUI {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorColor = kColor_L2;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.disFeeView];
    [self.view addSubview:self.payToolView];
    [self setPayToolViewWithTotalPrice:@"0.00" discountPrice:@"0.00"];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.equalTo(self.disFeeView.mas_top);
    }];
    
    [self.disFeeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(self.payToolView.mas_top);
    }];
    
    [self.payToolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(49);
        make.bottom.mas_equalTo(-LYSafeAreaBottom());
    }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark <UITableViewDelegate & UITableViewDataSource>
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return 44;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    static NSString* cellStr = @"cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
        
        if (indexPath.section == 0) {
            
            if (indexPath.row == 0) {
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                
                UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 65, 44)];
                label.textColor = kColor_1;
                label.text = @"停车场";
                label.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:label];
                
                parkingFiled = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 200, 44)];
                parkingFiled.textColor = kColor_1;
                parkingFiled.text = [[self.dataDic objectForKey:@"firstParkingInfo"] objectForKey:@"parkingName"];
                parkingFiled.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:parkingFiled];
            }
            else if (indexPath.row == 1) {
                
                UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 65, 44)];
                label.textColor = kColor_1;
                label.text = @"车牌号";
                label.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:label];
                
                UILabel* carNum = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 200, 44)];
                carNum.textColor = kColor_1;
                carNum.tag = 1001;
                carNum.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:carNum];
            }
            else if (indexPath.row == 2) {
                
                UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 65, 44)];
                label.textColor = kColor_1;
                label.text = @"有效期";
                label.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:label];
                
                UILabel* validDate = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 200, 44)];
                validDate.textColor = kColor_1;
                validDate.tag = 1002;
                validDate.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:validDate];
            }
        }
        else {
            if (indexPath.row == 0) {
                
                UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 65, 44)];
                label.textColor = kColor_1;
                label.text = @"办卡类型";
                label.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:label];
                
                UILabel* fee = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 200, 44)];
                fee.textColor = kColor_1;
                fee.tag = 1003;
                fee.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:fee];
            }
            else if (indexPath.row == 1) {
                
                UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 65, 44)];
                label.textColor = kColor_1;
                label.text = @"费用标准";
                label.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:label];
                
                UILabel* fee = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 200, 44)];
                fee.textColor = kColor_1;
                fee.tag = 1004;
                fee.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:fee];
            }
            else if (indexPath.row == 2) {
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                
                UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 65, 44)];
                label.textColor = kColor_1;
                label.text = @"缴存数";
                label.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:label];
                
                months = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 200, 44)];
                months.textColor = kColor_1;
                months.text = @"";
                months.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
                [cell.contentView addSubview:months];
            }
        }
    }
    UILabel* cardname = (UILabel*)[cell viewWithTag:1001];
    UILabel* time = (UILabel*)[cell viewWithTag:1002];
    UILabel* type = (UILabel*)[cell viewWithTag:1003];
    UILabel* fee = (UILabel*)[cell viewWithTag:1004];
    cardname.text = [[self.dataDic objectForKey:@"firstParkingInfo"] objectForKey:@"carNo"];
    time.text = [[self.dataDic objectForKey:@"firstParkingInfo"] objectForKey:@"expiredate"];
    type.text = [[self.dataDic objectForKey:@"firstParkingInfo"] objectForKey:@"cardname"];
    fee.text = [[self.dataDic objectForKey:@"firstParkingInfo"] objectForKey:@"monthlyfee"];
    
    return cell;
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1 && indexPath.row == 2) {
        
        NSDateFormatter* inputFormatter = [[NSDateFormatter alloc] init];
        inputFormatter.timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Beijing"];
        
        NSInteger yearDistance = 0;
        NSMutableArray* arr = [NSMutableArray array];
        NSString* dateStr = [[self.dataDic objectForKey:@"firstParkingInfo"] objectForKey:@"expiredate"];
        NSDate* date = [SEGUtils dateFromString:dateStr withFormatString:@"yyyy-MM-dd"];
        
        NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        unsigned int unitFlags = kCFCalendarUnitMonth;
        NSDateComponents* comps = [gregorian components:unitFlags fromDate:[NSDate date] toDate:date options:0];
        yearDistance = [comps month];
        
        for (int i = 0; i < 12; i++) {
            if (i < 12) {
                NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d", i + 1], @"num", nil];
                [arr addObject:dic];
            }
        }
        
        //月卡类型
        //        NSString *cardCode=[self.dataDic objectForKey:@"chargeStandardCode"];
        //
        //        if([cardCode isEqualToString:@"CRAD_MONTH"]){
        //
        //            NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        //            unsigned int unitFlags = kCFCalendarUnitMonth;
        //            NSDateComponents *comps = [gregorian components:unitFlags fromDate:[NSDate date]  toDate:date  options:0];
        //            yearDistance=[comps month];
        //
        //            for (int i=0; i<12; i++) {
        //                if (i<12) {
        //                    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",i+1],@"num", nil];
        //                    [arr addObject:dic];
        //                }
        //            }
        //
        //
        //        }else if ([cardCode isEqualToString:@"CRAD_QUARTER"]){
        //
        //            NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        //            unsigned int unitFlags = kCFCalendarUnitMonth;
        //            NSDateComponents *comps = [gregorian components:unitFlags fromDate:[NSDate date]  toDate:date  options:0];
        //            yearDistance=[comps month];
        //
        //            for (int i=0; i<12; i++) {
        //                if (i<12) {
        //                    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",i+1],@"num", nil];
        //                    [arr addObject:dic];
        //                }
        //            }
        //
        //
        //        }else if ([cardCode isEqualToString:@"CRAD_HALF"]){
        //
        //        }else if ([cardCode isEqualToString:@"CRAD_ALL"]){
        //
        //            NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        //            unsigned int unitFlags = kCFCalendarUnitYear;
        //            NSDateComponents *comps = [gregorian components:unitFlags fromDate:[NSDate date]  toDate:date  options:0];
        //            yearDistance=[comps year];
        //
        //            for (int i=0; i<3; i++) {
        //                if (i<3) {
        //                    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",i+1],@"num", nil];
        //                    [arr addObject:dic];
        //                }
        //            }
        //
        //        }else if ([cardCode isEqualToString:@"CRAD_VIP"]){
        //
        //        }
        if (arr.count > 0) {
            
            SEGCustomSecletViewController* customSelectView = [[SEGCustomSecletViewController alloc] init];
            customSelectView.dataArray = [NSArray arrayWithArray:arr];
            customSelectView.textKey = @"num";
            customSelectView.titleName = @"缴存数";
            customSelectView.selectDelegate = self;
            [self.navigationController pushViewController:customSelectView animated:YES];
        }
    }
    else if ((indexPath.section == 0 && indexPath.row == 0)) {
        
        SEGCustomSecletViewController* customSelectView = [[SEGCustomSecletViewController alloc] init];
        customSelectView.dataArray = _fieldArr;
        customSelectView.textKey = @"placeName";
        customSelectView.titleName = @"停车场";
        customSelectView.selectDelegate = self;
        [self.navigationController pushViewController:customSelectView animated:YES];
    }
}

// 设置分割线
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIEdgeInsets insets = UIEdgeInsetsZero;//屏幕等宽分割线
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:insets];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:insets];
    }
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:insets];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:insets];
    }
}

//比较时间
- (NSInteger)daysWithinEraFromDate:(NSDate*)startDate toDate:(NSDate*)endDate
{
    NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned int unitFlags = NSCalendarUnitSecond;
    NSDateComponents* comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
    long days = [comps second];
    return days;
}

#pragma mark -
#pragma mark customselectdelegate
- (void)selectedData:(id)data
{
    NSDictionary* dic = data;
    
    if ([[dic allKeys] containsObject:@"num"]) { //选择缴费周期
        months.text = [dic objectForKey:@"num"];
        
        //请求缴费结果信息接口
        NSDictionary* params2 = [[NSDictionary alloc] initWithObjectsAndKeys:
                                 [[self.dataDic objectForKey:@"firstParkingInfo"] objectForKey:@"cardtype"], @"cardtype",
                                 [dic objectForKey:@"num"], @"cycleLength",
                                 [[self.dataDic objectForKey:@"firstParkingInfo"] objectForKey:@"parkingPayField"], @"parkingPayField", nil];
        
        [[MonthCardRequestModel sharedRequestModel] requestPaymentChargeWithDictionary:params2 finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            
            NSDictionary* dict = result;
            if (!isSuccessed) { //数据返回异常
                [SEGAlertView showTmepMessageWithMessage:errorMessage];
            } else {
                expDate = [[[dict objectForKey:@"data"] objectForKey:@"newExpDate"] copy];
                paymentFee = [[[dict objectForKey:@"data"] objectForKey:@"paymentFee"] copy];

                [self setPayToolViewWithTotalPrice:[[dict objectForKey:@"data"] objectForKey:@"paymentFee"] discountPrice:[[dict objectForKey:@"data"] objectForKey:@"disFee"]];
            }
        }];
    }
    else { //选择停车场
        parkingFiled.text = [dic objectForKey:@"placeName"];
        NSDictionary* params2 = [[NSDictionary alloc] initWithObjectsAndKeys:[[self.dataDic objectForKey:@"firstParkingInfo"] objectForKey:@"carNo"], @"carNo",
                                 [dic objectForKey:@"communityParkingSeq"], @"communityParkingSeq", nil];
        
        
        [[MonthCardRequestModel sharedRequestModel] requestCarInfoWithDictionary:params2 finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            NSDictionary* dict = result;
            if (!isSuccessed) { //数据返回异常
                [SEGAlertView showTmepMessageWithMessage:kNetworkErrorMessage];
            } else {
                [self setPayToolViewWithTotalPrice:@"0.00" discountPrice:@"0.00"];
                months.text = @"";
                
                self.dataDic = [dict objectForKey:@"data"];
                [_tableView reloadData];
            }
        }];
    }
}

- (SEGPayToolView*)payToolView
{
    if (!_payToolView) {
        _payToolView = [[SEGPayToolView alloc] initWithFrame:CGRectMake(0, LYScreenHeight() - 49 - kNavigationBarAndStatusBarHeight - LYSafeAreaBottom(), LYScreenWidth(), 49)];
        _payToolView.showType = @"2";
        [_payToolView.titleBtn addTarget:self action:@selector(payToolViewClick) forControlEvents:UIControlEventTouchUpInside];
        [_payToolView.titleBtn setTitle:@"支付" forState:UIControlStateNormal];
        [_payToolView.titleBtn setBackgroundImage:[UIImage imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateDisabled];
    }
    return _payToolView;
}

- (void)payToolViewClick
{
    if (self.totalPrice > 0) {
        [SVProgressHUD show];
        WeakSelf;
        [[MonthCardRequestModel sharedRequestModel] requestPayMethodListWithCommunityId:kAccountCommunityID finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            [SVProgressHUD dismiss];
            NSDictionary* dict = result;
            if (!isSuccessed) { //数据返回异常
                [SEGAlertView showTmepMessageWithMessage:errorMessage];
                return;
            }
            //数据返回正常
            [[MonthCardRequestModel sharedRequestModel] requestPayMethodListWithRequestId:[dict objectForKey:@"data"] finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                NSDictionary* dict2 = result;
                if (!isSuccessed) { //数据返回异常
                    [SEGAlertView showTmepMessageWithMessage:kNetworkErrorMessage];
                    return;
                }
                
                NSMutableDictionary* param = [NSMutableDictionary dictionary];
                [param setObject:[[self.dataDic objectForKey:@"firstParkingInfo"] objectForKey:@"cardtype"] forKey:@"cardtype"];
                [param setObject:months.text forKey:@"cycleLength"];
                [param setObject:expDate forKey:@"newExpDate"];
                [param setObject:paymentFee forKey:@"paymentFee"];
                [param setObject:[[self.dataDic objectForKey:@"firstParkingInfo"] objectForKey:@"parkingPayField"] forKey:@"parkingPayField"];
                
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                [params setValue:@(SEGPayTypeName_MonthCard) forKey:@"payTypeName"];
                [params setValue:param forKey:@"dataDic"];
                [params setValue:[[dict2 objectForKey:@"data"] objectForKey:@"mentodInfos"] forKey:@"listData"];
                
                UIViewController *VC = [[SEGUhomeMediator sharedInstance] seg_initPayListViewController:params];
                [weakSelf.navigationController pushViewController:VC animated:YES];
            }];
        }];
    }
    else {
        [SEGAlertView showTmepMessageWithMessage:@"请选择缴存数"];
    }
}

///  设置支付优惠
- (void)setPayToolViewWithTotalPrice:(NSString*)totalPrice discountPrice:(NSString *)discountPrice
{
    self.totalPrice = [totalPrice floatValue];
    NSString *content = [NSString stringWithFormat:@"共计费用：%@元", totalPrice];
    
    NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:content];
    
    [attributedString addAttributes:@{
                                      NSFontAttributeName : [UIFont systemFontOfSize:13.f],
                                      NSForegroundColorAttributeName : kColor_1
                                      }
                              range:NSMakeRange(0, content.length)];
    
    [attributedString addAttributes:@{
                                          NSFontAttributeName : [UIFont systemFontOfSize:13.f],
                                          NSForegroundColorAttributeName : kColor_S1
                                          }
                                  range:[content rangeOfString:totalPrice]];
    
    self.payToolView.contentLabel.attributedText = attributedString;
    [self updateDiscountLabel:discountPrice];
}

- (void)updateDiscountLabel:(NSString *)discountPrice {
    if ([discountPrice doubleValue] == 0) {
        self.disFeeView.contentLabel.text = @"";
        [self.disFeeView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.equalTo(self.payToolView.mas_top);
        }];
    } else {
        self.disFeeView.contentLabel.text = [NSString stringWithFormat:@"(已优惠%@)", discountPrice];
        [self.disFeeView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.bottom.equalTo(self.payToolView.mas_top);
        }];
    }
}

- (SEGBillDeatilDisFeeView*)disFeeView
{
    if (!_disFeeView) {
        _disFeeView = [[SEGBillDeatilDisFeeView alloc] init];
        [_disFeeView setupUIWithIsHeader:NO];
    }
    return _disFeeView;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
